<?php

namespace App\Http\Middleware;

use App\Facade\AppContext;
use App\Utils\Output;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;

class AdminPermission
{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure $next
     * @param string $_action
     * @return mixed
     */
    public function handle($request, Closure $next, $_action = '')
    {
        list($controller, $action) = explode('@', Route::currentRouteAction());
        $preg = '#App\\\Http\\\Controllers\\\Admin\\\(.*?)Controller#is';
        $match = '';
        \preg_match_all($preg, $controller, $match);
        $controller = $match[1][0];
        if (!empty($_action)) {
            $action = $_action;
        }
        $controller = str_replace('_', '-', str_replace('\_', '/', Str::snake($controller)));
        if (!AppContext::can($action, $controller)) {
            if ($request->ajax()) {
                return response()->json(Output::fail( __('common.tips.no_permission'),-1));
            } else {
                return response(__('common.tips.no_permission'), 401);
            }
        }
        return $next($request);
    }
}
